import axios from 'axios';
import {MessageBox, Message} from 'element-ui';
import store from '@/store';
import {getToken} from '@/utils/auth';
import errorCode from '@/utils/errorCode';

const defaultSettings = require('@/settings');

// 是否显示重新登录
export const reLogin = {show: false};

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做一些事情

    // 让每个请求都携带token
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken();
    }

    return config;
  },
  error => {
    // 做一些请求出现错误的时候的事情
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || response.data.msg || errorCode['default'];
    // 二进制数据则直接返回
    if (response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer') {
      return response.data;
    }

    // 如果自定义代码不是200，则判断为错误。
    if (code !== 200) {
      Message({
        message: msg,
        type: 'error',
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(msg || 'Error'));
    } else {
      return response.data;
    }
  },
  error => {
    console.log('err' + error); // for debug

    let {message} = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      // 未设置状态码则默认成功状态
      const code = error.request.status;
      // 获取错误信息
      message = errorCode[code] || error.response.data.msg ||
        errorCode['default'];

      if (code === 401) {
        if (!reLogin.show) {
          reLogin.show = true;
          MessageBox.confirm('您已退出，您可以取消停留在此页面，或重新登录', '确认退出', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            reLogin.show = false;
            // 重新设置token
            store.dispatch('user/resetToken').then(() => {
              location.reload();
            });
          }).catch(() => {
            reLogin.show = false;
          });
        }
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
      }
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

export default service;
